<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="退款编号" prop="refundOrderNo">
        <el-input
          v-model="queryParams.refundOrderNo"
          placeholder="请输入本次退款编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="bizOrderNo">
        <el-input
          v-model="queryParams.bizOrderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入申请人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['greenold-refunds:refunds:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['greenold-refunds:refunds:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['greenold-refunds:refunds:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['greenold-refunds:refunds:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->
<!-- 状态筛选按钮组 -->
<div class="status-filter-area">
  <el-row :gutter="10" align="middle">
    <el-col>
      <el-button
        v-for="item in statusOptions"
        :key="item.value"
        :type="currentStatus === item.value ? 'primary' : 'default'"
        size="mini"
        class="status-btn"
        @click="handleStatusFilter(item.value)"
      >
        {{ item.label }}
      </el-button>
    </el-col>
  </el-row>
</div>

    <el-table v-loading="loading" :data="refundsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center">
      <template #default="scope">
         <!-- 计算逻辑：(当前页-1)*每页条数 + 当前页索引 + 1 -->
        {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="退款编号" align="center" prop="refundOrderNo" />
      <el-table-column label="订单号" align="center" prop="bizOrderNo" />
      <el-table-column label="退款金额" align="center" prop="amount" />
      <el-table-column label="申请人" align="center" prop="customerName" />
      <el-table-column label="申请时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ formatTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款时间" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span>{{ formatTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
         <!-- 订单状态（标签化显示） -->
      <el-table-column label="订单状态" align="center" prop="extend1">
        <template #default="scope">
          <el-tag 
            :type="orderStatusMap[scope.row.extend1]?.type" 
            effect="light"
          >
            {{ orderStatusMap[scope.row.extend1]?.label || '未知状态' }}
          </el-tag>
        </template>
      </el-table-column>
           <!-- 退款状态（标签化显示） -->
      <el-table-column label="退款状态" align="center" prop="refundStatus">
        <template #default="scope">
          <el-tag 
            :type="refundStatusMap[scope.row.refundStatus]?.type" 
            effect="light"
          >
            {{ refundStatusMap[scope.row.refundStatus]?.label || '未知状态' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button  link  type="primary"  icon="Eye"  @click="getRefundDetail(scope.row.id)"   v-hasPermi="['greenold-refunds:refunds:view']" >查看</el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['greenold-refunds:refunds:edit']">修改</el-button> -->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['greenold-refunds:refunds:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改退款记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="refundsRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  <!-- 查看退款记录弹窗（新增） -->
    <el-dialog
      title="查看退款记录"
      v-model="viewRefundDialogVisible"
      width="500px"
      append-to-body
    >
      <div class="refund-detail-container">
        <div class="detail-item">
          <span class="detail-label">退款编号</span>
          <span class="detail-value">{{ refundDetail.refundOrderNo || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">订单编号</span>
          <span class="detail-value">{{ refundDetail.bizOrderNo || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">订单状态</span>
          <el-tag 
            :type="orderStatusMap[refundDetail.extend1]?.type" 
            effect="light"
          >
            {{ orderStatusMap[refundDetail.extend1]?.label || '未知状态' }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="detail-label">退款状态</span>
          <el-tag 
            :type="refundStatusMap[refundDetail.refundStatus]?.type" 
            effect="light"
          >
            {{ refundStatusMap[refundDetail.refundStatus]?.label || '未知状态' }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="detail-label">申请人</span>
          <span class="detail-value">{{ scope.row.customerName || '未知' }}</span>
          <span 
            v-if="scope.row.source === 'backend'" class="backend-tag"
          >后台用户</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">申请时间</span>
          <span class="detail-value">{{ parseTime(refundDetail.createdAt, '{y}-{m}-{d} {h}:{i}') || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">退款原因</span>
          <span class="detail-value">{{ refundDetail.extend2 || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">退款渠道</span>
          <span class="detail-value">{{ refundDetail.refundChannel || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">退款方式</span>

          <span class="detail-value">{{ refundDetail.refundStatus || '无' }}</span>
        </div>
        <div v-if="refundDetail.refundStatus === '2'" class="detail-item">
          <span class="detail-label">失败状态码</span>
          <span class="detail-value">{{ refundDetail.returnCode || '无' }}</span>
        </div>
        <div v-if="refundDetail.refundStatus === '2'" class="detail-item">
          <span class="detail-label">失败原因</span>
          <span class="detail-value">{{ refundDetail.returnMsg || '无' }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewRefundDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>



  </div>
</template>

<script setup name="Refunds">
import { ref, reactive, toRefs, onMounted } from 'vue';
import { listRefunds, getRefunds, delRefunds, addRefunds, updateRefunds } from "@/api/greenold-refunds/refunds"
import { ElMessage } from 'element-plus';
import { formatTime } from '@/utils/date';

// 状态筛选相关
const currentStatus = ref(0); // 0=全部
const statusOptions = [
  { label: '全部', value: 0 },
  { label: '退款处理中', value: 1 },
  { label: '退款成功', value: 2 },
  { label: '退款失败', value: 3 },
];

// 退款状态映射（用于表格标签显示）
const refundStatusMap = reactive({
  '0': { label: '退款处理中', type: 'warning' },
  '1': { label: '退款成功', type: 'success' },
  '2': { label: '退款失败', type: 'danger' },
});
// 2. 筛选逻辑（强制参数更新+调试反馈）
const handleStatusFilter = (btnValue) => {
  // 强制更新当前状态（确保按钮高亮）
  currentStatus.value = btnValue;
  // 明确重置并设置筛选参数（与订单筛选逻辑一致）
  const statusMap = { 1: '0', 2: '1', 3: '2' }; // 按钮值→后端状态值映射
  queryParams.value.refundStatus = btnValue === 0 ? null : statusMap[btnValue];
  // 重置页码（避免筛选后页码残留）
  queryParams.value.pageNum = 1;
  // 打印参数（调试用，确认参数正确）
  // console.log('筛选参数：', { ...queryParams.value });
  // 重新查询
  getList();
};


const { proxy } = getCurrentInstance()

// 退款列表与基础状态
const refundsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 表单与查询参数
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    refundOrderNo: null,
    bizOrderNo: null,
    amount:null,
    customerName: null, // 新增：申请人姓名搜索
    createdBy: null,
    createdAt: null,
    refundStatus: null, // 关键：与后端筛选参数名一致
  },
  rules: {
  }
})
console.log("data",data)

const { queryParams, form, rules } = toRefs(data)


// ========== 状态映射（核心：订单/退款状态标签化） ==========
// 订单状态映射：extend1值 → {标签文字, 标签类型}
const orderStatusMap = reactive({
  '0': { label: '待执行', type: 'info' },
  '1': { label: '已执行', type: 'success' },
  '2': { label: '已退款', type: 'warning' },
});


// // 退款状态映射：refundStatus值 → {标签文字, 标签类型}
// const refundStatusMap = reactive({
//   '0': { label: '退款处理中', type: 'warning' },
//   '1': { label: '退款成功', type: 'success' },
//   '2': { label: '退款失败', type: 'danger' },
// });



// ========== 查看退款弹窗逻辑（新增） ==========
const viewRefundDialogVisible = ref(false); // 弹窗显隐
const refundDetail = ref({}); // 退款详情数据
const currentRefundId = ref(''); // 当前查看的退款ID

// 获取退款详情
const getRefundDetail = async (id) => {
  currentRefundId.value = id;
  try {
    const res = await getRefunds(id); // 调用“查询单条退款”接口
    if (res.code === 200) {
      refundDetail.value = res.data;
      viewRefundDialogVisible.value = true;
    } else {
      ElMessage.error(res.msg || '获取退款详情失败');
    }
  } catch (error) {
    ElMessage.error('网络异常，无法获取退款详情');
    console.error('获取退款详情异常：', error);
  }
};









function getList() {
  loading.value = true;
  // 调用接口时明确传递参数（与订单筛选逻辑一致）
  listRefunds({ ...queryParams.value }).then(response => {
    // console.log('接口返回数据：', response); // 调试用，确认返回数据符合筛选
    console.log('退款列表数据：', response.rows); // 检查每条记录是否有customerName
    refundsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    // console.error('筛选请求失败：', error); // 捕获错误
    loading.value = false;
    ElMessage.error('筛选失败，请重试');
  });
}
// 5. 重置逻辑（同步重置状态按钮）
function resetQuery() {
  proxy.resetForm("queryRef");
  // 重置状态筛选（与订单筛选逻辑一致）
  currentStatus.value = 0;
  queryParams.value.refundStatus = null;
  handleQuery();
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    tradeOrderNo: null,
    refundOrderNo: null,
    bizOrderNo: null,
    amount: null,
    refundAmount: null,
    createdBy: null,
    customerName: null, // 新增：存储申请人姓名
    createdAt: null,
    updatedAt: null,
    extend1: null,
    refundStatus: null,
    merchantNo: null,
    refundChannel: null,
    returnCode: null,
    returnMsg: null,
    orderRemark: null,
    originalAmount: null,
    updatedBy: null,
    remark: null,
    source: null,
    extend2: null
  }
  proxy.resetForm("refundsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}



// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加退款记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRefunds(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改退款记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["refundsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRefunds(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRefunds(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除退款记录编号为"' + _ids + '"的数据项？').then(function() {
    return delRefunds(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

// /** 导出按钮操作 */
// function handleExport() {
//   proxy.download('greenold-refunds/refunds/export', {
//     ...queryParams.value
//   }, `refunds_${new Date().getTime()}.xlsx`)
// }

// 初始化加载数据
onMounted(() => {
  getList();
});
</script>

<style scoped>
/* 退款详情弹窗样式 */
.refund-detail-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-label {
  width: 120px;
  color: #666;
  text-align: right;
  margin-right: 16px;
}

.detail-value {
  flex: 1;
  color: #333;
}

/* 后台用户标签样式 */
.backend-tag {
  background-color: #f5a623;
  color: #fff;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
}
</style>